package com.linln.wxapi;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;

import com.linln.wxapi.config.WxMaProperties;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.linln.common.exception.ResultException;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.fileUpload.FileUpload;
import com.linln.component.fileUpload.enums.UploadResultEnum;
import com.linln.modules.system.domain.Upload;
import com.linln.modules.system.service.UploadService;
import com.linln.wxapi.config.WxMaConfiguration;


/**
 * @author 小懒虫
 * @date 2018/11/02
 */

@RequestMapping("/wx")
@RestController
public class WxUploadController {

    @Autowired
    private UploadService uploadService;

    /**
     * 上传web格式图片
     */
    @PostMapping("/upload/image")
    @ResponseBody
    public ResultVo uploadImage(@RequestParam("image") MultipartFile multipartFile) {

        // 创建Upload实体对象
        Upload upload = FileUpload.getFile(multipartFile, "/images");
        if(!checkPick(upload.getUrl())) {
            return ResultVoUtil.error("违规图片");
        }else {
        	System.out.println("我正规");
        }
        try {
            return saveImage(multipartFile, upload);
        } catch (IOException | NoSuchAlgorithmException e) {
            System.out.println("我报错了");

            return ResultVoUtil.error("上传图片失败");
            
        }
    }

   
    /**
     * 保存上传的web格式图片
     */
    private ResultVo saveImage(MultipartFile multipartFile, Upload upload) throws IOException, NoSuchAlgorithmException {
        // 判断是否为支持的图片格式
        String[] types = {
                "image/gif",
                "image/jpg",
                "image/jpeg",
                "image/png"
        };
        if(!FileUpload.isContentType(multipartFile, types)){
            throw new ResultException(UploadResultEnum.NO_FILE_TYPE);
        }

        // 判断图片是否存在
        Upload uploadSha1 = uploadService.getBySha1(FileUpload.getFileSha1(multipartFile));
        if (uploadSha1 != null) {
            System.out.println("我来了>>>>>"+uploadSha1.getPath());

            return ResultVoUtil.success(uploadSha1);
        }
         System.out.println("我到这里了");
        FileUpload.transferTo(multipartFile, upload);
        System.out.println("我上传成功了");
        // 将文件信息保存到数据库中
        uploadService.save(upload);
        System.out.println("我保存了");

        return ResultVoUtil.success(upload);
    }
    
    
    /**
     *  恶意图片过滤
     * @return
     */
    public static Boolean checkPick(String images) {
        try {
        	//images="http://www.xzwbfuwu.cn/upload/images/20200612/c7ce18bf00c54f01bff36aa3fb8bb2c9.jpg";
        	String token=WxMaConfiguration.getWxMaService().getAccessToken();
        	System.out.println("token----------->"+token);
        	//String token=WxMaConfiguration.getMaService(ConstUtil.appid).getAccessToken();
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/img_sec_check?access_token=" +token );
            request.addHeader("Content-Type", "application/octet-stream");
            InputStream inputStream = returnBitMap(images);
            byte[] byt = new byte[inputStream.available()];
            inputStream.read(byt);
            request.setEntity(new ByteArrayEntity(byt, ContentType.create("image/jpg")));
            response = httpclient.execute(request);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
            JSONObject jso = JSONObject.parseObject(result);
            System.out.println(jso + "-------------验证效果");
            Object errcode = jso.get("errcode");
            int errCode = (int) errcode;
            if (errCode == 0) {
                return true;
            } else if (errCode == 87014) {
                System.out.println("图片内容违规-----------");
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("----------------调用腾讯内容过滤系统出错------------------");
            return true;
        }
    }
    
    
    public static void main(String[] args) {
		String url="https://www.xzwbfuwu.cn/upload/images/20200613/3177cd12dc944533bcc0a867d359c979.jpg";
		checkPick(url);
	}
    
    /**
     * 通过图片url返回图片Bitmap
     * @param path
     * @return
     */
    public  static InputStream returnBitMap(String path) {
        URL url = null;
        InputStream is =null;
        try {
            url = new URL(path);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();    //得到网络返回的输入流

        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }

}
